package com.ruoyi.web.controller.distribution;

import cn.distribution.groupManager.service.GroupManagerService;
import cn.distribution.messagesManager.service.MessagesManagerService;
import cn.distribution.officeManager.service.OfficeService;
import cn.distribution.personManager.service.PersonManagerService;
import cn.distribution.projectManager.service.ProjectService;
import cn.distribution.receiptManager.entity.vo.ReceiptVO;
import cn.distribution.receiptManager.service.ReceiptService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.TokenService;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.*;

/**
 * @author  xiayujia
 */
@RestController
@RequestMapping("/distribution/receiptManager")
public class ReceiptManagerController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(GroupManagerController.class);

    @Autowired
    private ProjectService projectService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private GroupManagerService groupManagerService;

    @Autowired
    private PersonManagerService personManagerService;

    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private MessagesManagerService messagesManagerService;
    private String officeName;
    private Date beginTime;
    private Date endTime;

    @GetMapping("/getReceipt")
    public TableDataInfo getReceiptList(String officeName, Date beginTime, Date endTime)
    {

        List<ReceiptVO> dataSendList;
        Long receiptId= SecurityUtils.getLoginUser().getUser().getUserId();
        dataSendList=this.receiptService.getReceiptList(receiptId,officeName,beginTime,endTime);
        System.out.println(dataSendList);
//        logger.info(dataSendList.toString());
        return getDataTable(dataSendList);
    }
    @GetMapping("/deleteOffice")
    public String deleteoffice(Long id)
    {
        this.receiptService.deleteOffice(id);
        String s="删除成功";
        return s;
    }


    /**
     * @author zhengminjie
     */
    @GetMapping("/table")
    public Map<String,List<String>> table(Long officeId)
    {
        Map<String,List<String>> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        List<String> data = new ArrayList<>();
        String filePath = System.getProperty("user.dir") + "\\" + this.officeService.getById(officeId).getOfficePath();
        File file = new File(filePath);
        String fileName = file.getName();
        try {
            if (fileName.charAt(fileName.length() - 1) == 's') {
                HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
                HSSFSheet sheet = workbook.getSheetAt(0);
                HSSFRow titleRow = sheet.getRow(0);
                for(int i = 0; i <titleRow.getLastCellNum(); i++){
                    list.add(String.valueOf(titleRow.getCell(i)));
                }
                for(int i = 1; i <= sheet.getLastRowNum(); i++){
                    HSSFRow row = sheet.getRow(i);
                    HSSFCell cell = row.getCell(this.officeService.getById(officeId).getExcelColumn() - 1);
                    cell.setCellType(CellType.STRING);
                    StringBuilder string = new StringBuilder();
                    for(int j = 0; j<row.getLastCellNum(); j++){
                        string.append(row.getCell(j)).append(",");
                    }
                    string = new StringBuilder(string.substring(0, string.length() - 1));
                    data.add(string.toString());
                }
                map.put("header",list);
                map.put("data",data);
            }
            else {
                XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
                XSSFSheet sheet = workbook.getSheetAt(0);
                XSSFRow titleRow = sheet.getRow(0);
                for(int i = 0; i <titleRow.getLastCellNum(); i++){
                    list.add(String.valueOf(titleRow.getCell(i)));
                }
                for(int i = 1; i <= sheet.getLastRowNum(); i++){
                    XSSFRow row = sheet.getRow(i);
                    XSSFCell cell = row.getCell(this.officeService.getById(officeId).getExcelColumn() - 1);
                    cell.setCellType(CellType.STRING);
                    StringBuilder string = new StringBuilder();
                    for(int j = 0; j<row.getLastCellNum(); j++){
                        string.append(row.getCell(j)).append(",");
                    }
                    string = new StringBuilder(string.substring(0, string.length() - 1));
                    data.add(string.toString());
                }
                map.put("header",list);
                map.put("data",data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @author zhengminjie
     */
    @GetMapping("/Word")
    public String Word (Long id) throws IOException{
        String filePath = System.getProperty("user.dir") + "\\" + this.officeService.getById(this.receiptService.getById(id).getOfficeId()).getOfficePath();
        File file = new File(filePath);
        File[] temp = file.listFiles();
        Long groupId = this.receiptService.getById(id).getGroupId();
        Long userId = this.receiptService.getById(id).getReceiptId();
        for(int i = 0; i<temp.length; i++){
            String name = temp[i].getName();
            name = name.substring(0,name.lastIndexOf("."));
            if(this.personManagerService.getAllById(groupId, userId).getUserNumber()==null){
                return "无";
            }
            if(name.equals(this.personManagerService.getAllById(groupId, userId).getUserNumber().toString())){
                if (temp[i].getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
                    InputStream is = new FileInputStream(filePath+"\\"+temp[i].getName());
                    XWPFDocument document = new XWPFDocument(is);
                    String value = "";
                    try {
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        XHTMLConverter.getInstance().convert(document, outputStream, null);

                        value = new String(outputStream.toByteArray());
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    return value;
                } else if(temp[i].getName().endsWith(".doc") || temp[i].getName().endsWith(".DOC")){
                    InputStream input = new FileInputStream(temp[i]);
                    HWPFDocument wordDocument = new HWPFDocument(input);
                    String content = null;
                    ByteArrayOutputStream baos = null;
                    try {
                        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                        wordToHtmlConverter.processDocument(wordDocument);
                        Document htmlDocument = wordToHtmlConverter.getDocument();
                        DOMSource domSource = new DOMSource(htmlDocument);
                        baos = new ByteArrayOutputStream();
                        StreamResult streamResult = new StreamResult(baos);

                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer serializer = tf.newTransformer();
                        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
                        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                        serializer.setOutputProperty(OutputKeys.METHOD, "html");
                        serializer.transform(domSource, streamResult);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (baos != null) {
                                content = new String(baos.toByteArray(), "utf-8");
                                baos.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return content;
                }
            }
        }
        String html = "无";
        return html;
    }


    /**
     * @author zhengminjie
     */
    @GetMapping("/getWordList")
    public List<Map<String,String>> getWordList(Long id){
        List<Map<String,String>> list = new ArrayList();
        String filePath = System.getProperty("user.dir") + "\\" + this.officeService.getById(this.receiptService.getById(id).getOfficeId()).getOfficePath();
        File file = new File(filePath);
        File[] temp = file.listFiles();
        for(int i = 0; i<temp.length; i++){
            String name = temp[i].getName();
            Map<String,String> map = new HashMap<>();
            name = name.substring(0,name.lastIndexOf("."));
            map.put("name", String.valueOf(i));
            map.put("title",name);
            if (temp[i].getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
                InputStream is = null;
                try {
                    is = new FileInputStream(filePath+"\\"+temp[i].getName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                XWPFDocument document = null;
                try {
                    document = new XWPFDocument(is);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String value = "";
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    XHTMLConverter.getInstance().convert(document, outputStream, null);

                    value = new String(outputStream.toByteArray());
                } catch (Exception e){
                    e.printStackTrace();
                }
                map.put("content",value);
            } else if(temp[i].getName().endsWith(".doc") || temp[i].getName().endsWith(".DOC")){
                InputStream input = null;
                try {
                    input = new FileInputStream(temp[i]);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                HWPFDocument wordDocument = null;
                try {
                    wordDocument = new HWPFDocument(input);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String content = null;
                ByteArrayOutputStream baos = null;
                try {
                    WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                    wordToHtmlConverter.processDocument(wordDocument);
                    Document htmlDocument = wordToHtmlConverter.getDocument();
                    DOMSource domSource = new DOMSource(htmlDocument);
                    baos = new ByteArrayOutputStream();
                    StreamResult streamResult = new StreamResult(baos);

                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer serializer = tf.newTransformer();
                    serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
                    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                    serializer.setOutputProperty(OutputKeys.METHOD, "html");
                    serializer.transform(domSource, streamResult);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (baos != null) {
                            content = new String(baos.toByteArray(), "utf-8");
                            baos.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                map.put("content",content);
            }
            list.add(map);
        }
        return list;
    }
}
